package com.huan.springcloud.mongo;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LetterController {
    @Autowired
    private LetterServiceImpl letterService;
    private static final int PAGE_SIZE=5;

    @ResponseBody
    @RequestMapping("/addLetter")
    public Object addLetter(){
        Letter letter=new Letter("xadgjadbhjas",1,"小翟","titlename","content__is","创建时间","发布时间");
        List<Letter> lst=new ArrayList<>();
        for(int i=0;i<10;++i){
            lst.add(new Letter("xadgjadbhjas"+('a'*i),i+1,"小翟"+i,"titlename"+i,"content__is","创建时间","发布时间"));
        }
        for (Letter let : lst) {
            letterService.addLetter(let);
        }
        return lst;
    }
    @ResponseBody
    @RequestMapping("/findLetters")
    public List<Letter> findLetter(){
        return letterService.selectAllLetters();
    }

    @ResponseBody
    @RequestMapping("/letterPage/{curPage}")
    public Object letterPage(@PathVariable int curPage){
        LetterPage letterPage=new LetterPage();
        letterPage.setCurrentpage(curPage);
        letterPage.setTotalcount(letterService.letterCount());//查总数
        letterPage.setPagesize(PAGE_SIZE);

        List<Letter> letters=letterService.selectLettersByPage(curPage,PAGE_SIZE);
        letterPage.setLetters(letters);
        return letterPage;
    }

    @ResponseBody
    @RequestMapping("/deleteLetter/{id}")
    public String deleteLetter(@PathVariable String id){
        Map<String,Object> map=new HashMap<>();
        if(id!=null){
            DeleteResult deleteResult = letterService.deleteLetterById(id);
            if (deleteResult!=null){
                return JSONObject.toJSONString(deleteResult);
            }
            map.put("state",0);
            map.put("info","error");
            return JSONObject.toJSONString(map);
        }
        map.put("state",0);
        map.put("info","error");
        return JSONObject.toJSONString(map);
    }
}